<template>
  <div class="smart-plan-dynamic-info">
    <!-- 动态信息 -->
    <base-timeline
      :data="recordPage.list"
      :record-render="renderRecord"
      :loading="recordLoading"
      :loadmore="recordPage.hasNextPage"
      @load="loadMore" 
    />
  </div>
</template>
<script>
import Page from '@model/Page';
import { isOpenData } from '@src/util/platform';
import { formatDate } from 'pub-bbx-utils'
// api
import { getIntelligentPlanRecord } from '@src/modules/smartPlan/api/index.js';
import { t } from '@src/locales';
/* mixin */
import SmartPlanMixin from '@src/modules/smartPlan/mixin/index.js'

export default {
  name: 'smart-plan-dynamic-info',
  mixins: [SmartPlanMixin],
  props: {
    planId: {
      type: [String, Number],
      default: '',
    },
    planTypeName: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      recordLoading: false,
      recordPage: new Page(), // 页面数据
      params: {
        id: this.planId,
        pageNum: 1,
        pageSize: 15,
      },
    };
  },
  mounted() {
    this.searchRecord();
  },
  methods: {
    // 获取动态信息
    getRecordList(params) {
      return getIntelligentPlanRecord(params);
    },

    // 查询信息动态
    async searchRecord() {
      try {
        this.recordLoading = true;
        let res = await this.getRecordList(this.params);

        this.recordPage.list = [];
        let result = res?.data || {};

        this.recordPage.merge(result);
        this.$emit('getRecordCount', result.total);
      } catch (error) {
        console.error(`searchRecord ${error}`);
      } finally {
        this.recordLoading = false;
      }
    },

    // 加载更多
    async loadMore() {
      try {
        this.params.pageNum++;
        this.recordLoading = true;

        let res = await this.getRecordList(this.params);
        let result = res.data || {};

        this.recordPage.merge(result);
      } catch (error) {
        console.error(`product template record loadMore err ${error}`);
      } finally {
        this.recordLoading = false;
      }
    },

    /** 渲染用户 */
    renderUserName(userName, staffId, userId) {
      return <recordUserName userName={userName} staffId={staffId} userId={userId} />
    },

    /** 根据记录的action渲染对应的内容，支持jsx和render函数 */
    renderRecord(h, record) {
      let { action, userName, staffId, userId, content, planNumber } = record || {};
      if (content) content = JSON.parse(content)

      if (['创建', '取消', '删除任务'].includes(action)) {
        return [
          <i18n path={`common.record.smartPlan['${action}']`} tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
            <span place="planNo">{planNumber}</span>
          </i18n>,
          action == '删除任务' ? (
            <p>{t('task.taskTypes.planTask.estimatedCreationTime')}: {formatDate(content.planTime)}</p>
          ) : ('')
        ];
      }

      if (action === '编辑') {
        return [
          <i18n path={`common.record.smartPlan['${action}']`} tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
            <span place="planNo">{planNumber}</span>
          </i18n>,
          content?.updateFields ? (
            <p>
              {t('common.base.modifyField')}: 
              {content?.updateFields || ''}
            </p>
          ) : (
            ''
          ),
        ];
      }

      if (action === '移除') {
        return [
          <i18n path={`common.record.smartPlan['${action}']`} tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
            <span place="data1">{content.updateField}</span>
            <span place="data2">{content.updateValue}</span>
          </i18n>,
        ];
      }

      if (action === '调整时间') {
        return [
          <i18n path={`common.record.smartPlan['${action}']`} tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
            <span place="data1">{formatDate(content.beforeAdjustTime)}</span>
            <span place="data2">{formatDate(content.adjustTime)}</span>
            <span place="planNo">{planNumber}</span>
          </i18n>,
        ];
      }

      if (action === '调整联系人') {
        return [
          <i18n path={`common.record.smartPlan['${action}']`} tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
            <span place="type">{content.createDimension == 1 ? t('common.base.customer') : t('common.base.product')}</span>
            <span place="serialNumber">{content.objectNo}</span>
          </i18n>,
          <p>{t('smartPlan.newLinkman')}：{content.linkmanName} {content.linkmanPhone}</p>
        ];
      }

      if (action === '立即创建') {
        return [
          <i18n path={`common.record.smartPlan['${action}']`} tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
            {planNumber == '创建失败' ? <span place="planNo">{planNumber}</span> : <span place="planNo" onClick={() => this.openBizDetail(content)} class="link-text">{planNumber}</span>}
          </i18n>,
        ];
      }

      if (action === '创建失败') {
        const nameList = content.nameList || []
        const displayName = content.fieldName == 'customer' ? t('common.label.customerName') : t('common.label.productName')
        return [
          <i18n path={`common.record.smartPlan['${action}']`} tag="h5">
            <span place="planNo">{planNumber}</span>
          </i18n>,
          <p>{t('common.record.linkcOrder.failCause')}: {content.errorMessage}</p>,
          <p>{displayName}: {nameList.join(',')}</p>
        ];
      }

      if (action === '指派失败') {
        return [
          <i18n path={`common.record.smartPlan['${action}']`} tag="h5">
            <span place="planNo">{planNumber}</span>
          </i18n>,
          <p>{t('common.record.linkcOrder.failCause')}: {content.errorMessage}</p>,
          <p>{t('common.projectManage.detail.projectTaskId')}: {content.jobNo}</p>
        ];
      }

      return [
        <i18n path={`common.record.smartPlan['${action}']`} tag="h5">
          <span place="operator">{this.renderUserName(userName, staffId)}</span>
        </i18n>
      ];
    },
    // 打开业务详情页面
    openBizDetail(content) {
      content.planTypeName = this.planTypeName
      const { createBizId, createBizType } = content
      if (createBizType == 'TASK') {
        return this.openTaskTab(createBizId)
      } else if (createBizType == 'EVENT') {
        return this.openEventDetailTab(createBizId)
      } else if (createBizType == 'PAAS') {
        return this.openPassTab(content)
      }
    }
  },
};
</script>
<style lang="scss" scoped>
.smart-plan-dynamic-info {
  height: 100%;
  overflow-y: auto;
  background: #fff;
}
</style>